import com.googlecode.linkmein.domain.*
import com.googlecode.linkmein.service.FetchEmployeeService
import grails.converters.JSON

class WorkmatesController {
    FetchEmployeeService fetchEmployeeService

    def allowedMethods = [add: 'POST', index: 'GET', list: 'GET']

    def beforeInterceptor = {
        if (!session.getAttribute("gmail")){
            flash["error"] = "Please login with your google account and make sure your google account is in our list."
            redirect(uri: "/error.gsp")
            return false
        }
    }

    def index = {
    }

    def list = {
        YIM yahoo = session.getAttribute("yim")
        MSN msn = session.getAttribute("msn")
        InstantMessenger[] messengers = [yahoo, msn];
        Employee currentUser = fetchEmployeeService.getEmployees().findByAnyIMId(messengers);
        Map projects = fetchEmployeeService.getProjects().orderedByProjects()

        render contentType: 'text/plain', text: [workmates: flatten(projects), currentUser: flatten(currentUser)] as JSON
    }

    def show = {
        Employees employees = fetchEmployeeService.getEmployees()
        def employee = employees.findByName(new Name(params.name, "only compare english name"))
        if (employee == Employee.NULL) {
            flash["error"] = "The person you are requesting does not exist"
            redirect(uri: "/error.gsp")
        }
        else {
            render(view: "show", model: [employee: employee,
                    prevEmployee: employees.getPrevEmployee(employee),
                    nextEmployee: employees.getNextEmployee(employee)])
        }
    }

    private Map flatten(Map<Project, Employees> projects) {
        def result = [:]
        projects.each {
            def members = []
            it.value.each {
                members.add(flatten(it))
            }
            result[it.key.name] = members
        }
        return result;
    }

    private Object flatten(Employee e) {
        return [
                englishName: e.englishName,
                shrinkedEnglishName: e.shrinkedEnglishName,
                chineseName: e.chineseName,
                MSN: e.MSN,
                YIM: e.YIM,
                blog: e.blog
        ];
    }
}